package com.why.controller;


import org.springframework.http.*;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author why
 * @since 2022-02-22
 */
@RestController
@RequestMapping("/why/t-user")
public class RedisTemplateController {

    @Resource
    private RestTemplate restTemplate;

    @GetMapping("/proxy")
    public Object proxy(HttpServletRequest request, @RequestBody Map<String, Object> map) {


        String method = request.getHeader("method").toUpperCase();
        String module = request.getHeader("module");
        String uri = request.getHeader("uri");

        StringBuffer uriAll = new StringBuffer();
        uriAll.append("http://").append(module).append(uri);


        if (method.equals("GET") || method.equals("DELETE") || method.equals("OPTIONS")) {

            return getMethod(request, uriAll, method);
        }
        if (method.equals("POST") || method.equals("PATCH") || method.equals("PUT")) {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.valueOf(MediaType.APPLICATION_JSON_VALUE));
            HttpEntity<Map<String, Object>> entity = new HttpEntity<>(map, headers);
            ResponseEntity<Object> exchange = restTemplate.exchange(uriAll.toString(), Objects.requireNonNull(HttpMethod.resolve(method)), entity, Object.class);
            Object body = exchange.getBody();
            System.out.println("------------------------------------" + body);

            return body;
        }

        return "iii";

    }


    private Object getMethod(HttpServletRequest request, StringBuffer uriAll, String method) {

        //获取所有参数
        Enumeration<String> parameterNames = request.getParameterNames();
        StringBuffer stringBuffer = new StringBuffer();
        //拼接uri路径
        while (parameterNames.hasMoreElements()) {
            String param = parameterNames.nextElement();
            stringBuffer.append(param).append("=").append(request.getParameter(param)).append("&");
        }
        if (!StringUtils.isEmpty(stringBuffer)) {
            String paramAll = "?" + stringBuffer.deleteCharAt(stringBuffer.length() - 1);
            uriAll.append(paramAll);
        }

        if (method.equals("OPTIONS")) {
            try {
                Set<HttpMethod> httpMethods = restTemplate.optionsForAllow(String.valueOf(uriAll));
            } catch (RestClientException e) {
                return Boolean.FALSE;
            }
            return Boolean.TRUE;
        }
        Object object = restTemplate.getForObject(uriAll.toString(), Object.class);

        System.out.println(object);
        return object;
    }
}
